var express = require('express')();
var Router  = require('./Router');
var DomainConfiger = require('./DomainConfiger');


var Core = {

    listen: function( port ) {

        var self = this;

        express.all( '*', function( req, res ) {
            self.route( req, res );
        });

        express.listen( port || 80 );
        
    },

    route: function( req, res ) {
        
        var hostName    = req.hostname,
            reqURL      = req.url,
            reqURI      = removeQueryString(reqURL);

        var appName     = DomainConfiger.getAppName(hostName);

        if( !appName )
            throw new Error('appName not found by domain: ' + hostName );
        

        Router.setControllersDir( this.appsDir + '/controllers/' + appName );

        Router.to( reqURI, req, res );

        /**
         * 移除URL后的query参数
         */
        function removeQueryString( URL ) {

            var queryStringPosi = URL.indexOf('?');

            if( queryStringPosi>0 )
                return URL.substr( 0, queryStringPosi );
            else
                return URL;

        }

    },

    setAppsDir: function( absolutePath ) {
        this.appsDir = absolutePath;
    },

    onDomain: function( domainRegexStr ) {
        var domainConfiger = new DomainConfiger( domainRegexStr );

        return domainConfiger;
    }

};

module.exports = Core;